#pragma once
#ifndef DBLIST_H
#define DBLIST_H

#include <queue>
#include <mutex>
#include <string>
#include <semaphore.h>
#include "db.h"

//数据库连接池类
class mysql_connPool{
public:
    mysql_connPool();
    ~mysql_connPool();

    //不允许拷贝
    mysql_connPool(const mysql_connPool&)=delete;
    mysql_connPool& operator=(const mysql_connPool&)=delete;
    

    //返回单例对象
    static mysql_connPool* getInstance();

public:
    //从连接池中获取一个连接
    MySQL* get_conn();

    //释放一个连接，将其放回连接池
    bool release_conn(MySQL* conn);

    //连接池初始化
    bool init(string url,string user,string password,string database,int port,int maxConn);

    //释放所有连接
    void destory_pool();

private:
    //连接队列
    std::queue<MySQL*> m_pool;
    
    //记录最大连接量
    int max_conn;

    //当前正在使用的连接
    int cur_conn;

    //当前空闲连接
    int free_conn;

    //数据库连接用户账号
    std::string m_user;

    //数据库连接用户密码
    std::string m_password;

    //数据库地址
    std::string m_url;

    //数据库端口
    int m_port;

    //数据库名
    std::string m_database;

private:
    //同步相关

    //用于操作队列的互斥锁
    std::mutex m_lock;

    //用于队列中连接数量的信号量
    sem_t m_sem;
    
};

//RAII类
class mysql_connpool_RAII{
public:
    mysql_connpool_RAII(MySQL** conn,mysql_connPool* connPool);
    ~mysql_connpool_RAII();
private:
    MySQL* m_connRAII;
    mysql_connPool* connPool;
};

#endif